package com.adonis.ejoy.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.adonis.ejoy.R;
import com.adonis.ejoy.utils.FixGridLayout;
import com.adonis.ejoy.utils.HttpUtil;
import com.yanzhenjie.album.Album;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.Response;

import static android.app.Activity.RESULT_OK;

public class PostFragment extends Fragment {

    @BindView(R.id.image_list)
    FixGridLayout image_list;           //通过注解实例化的控件不能是私有的
    @BindView(R.id.text_post)
    EditText text_post;
    @BindView(R.id.btn_imag_add)
    ImageButton btn_imag_add;

    private int uid;
    private static final int CHOOSE_PHOTO=2;
    private View view = null;
    private int chooseable=9;
    private List<String> photoList = new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_post, container, false);
        ButterKnife.bind(this,view);
        uid = ((TextView)getActivity().findViewById(R.id.user_info)).getMaxWidth();
        text_post.setFocusable(true);
        text_post.setFocusableInTouchMode(true);
        text_post.requestFocus();
//      getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); //输入框获取焦点并弹出软键盘

        WindowManager wmManager=(WindowManager) view.getContext().getSystemService(Context.WINDOW_SERVICE); //获取屏幕宽度
        int with=wmManager.getDefaultDisplay().getWidth()/3;
        image_list.setmCellHeight(with);
        image_list.setmCellWidth(with);
        return view;
    }

    @OnClick({R.id.btn_cancel,R.id.btn_post,R.id.btn_imag_add})
    public void onClick(View v){
        switch (v.getId()){
            case R.id.btn_post:
                post();
                break;
            case R.id.btn_cancel:
                clearPost();
                Toast.makeText(view.getContext(), "post cancel", Toast.LENGTH_SHORT).show();
                break;
            case R.id.btn_imag_add:
                if(ContextCompat.checkSelfPermission(v.getContext(), android.Manifest.permission.WRITE_EXTERNAL_STORAGE)!=
                        PackageManager.PERMISSION_GRANTED){
                    ActivityCompat.requestPermissions(this.getActivity(),new String[]{"android.Manifest.permission.WRITE_EXTERNAL_STORAGE"},1);
                }else{
                    Album.startAlbum(this, CHOOSE_PHOTO,chooseable);
                }
                break;
        }
    }

    private void post() {
        String text=text_post.getText().toString();
        MediaType mediaType = MediaType.parse("text/form-data; charset=utf-8");

        MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("id",new String(uid+""))
                .addFormDataPart("text",text)
                .addFormDataPart("photo",photoList.toString());
        //循环添加文件
        for (int i = 0; i < photoList.size(); i++) {
            File file = new File(photoList.get(i));
            requestBodyBuilder.addFormDataPart("imgs", file.getName(), RequestBody.create(mediaType, new File(photoList.get(i))));
        }

        String url = "http://10.0.2.2:8080/Ejoy/mvc/upload";
        RequestBody body = requestBodyBuilder.build();

        HttpUtil.sendPostRequest(url, body,new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("onFailure: ", "failed");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("response: ", response.body().string());
                Log.d("onSuccess: ", "successful");
            }
        });
        clearPost();
    }

    public static String getMimeType(String filePath) {
        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
        String mime = "text/plain";
        if (filePath != null) {
            try {
                mmr.setDataSource(filePath);
                mime = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE);
            } catch (IllegalStateException e) {
                return mime;
            } catch (IllegalArgumentException e) {
                return mime;
            } catch (RuntimeException e) {
                return mime;
            }
        }
        return mime;
    }
    private void clearPost() {
        text_post.setText("");
        image_list.removeAllViews();
        photoList.clear();
        chooseable = 9;
        image_list.addView(btn_imag_add);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 1:
                if(grantResults.length>1 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
                    Album.startAlbum(this, CHOOSE_PHOTO,chooseable);
                }else {
                    Toast.makeText(this.getContext(), "you denied the permission", Toast.LENGTH_SHORT).show();
                }
                break;
            default: break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            case CHOOSE_PHOTO:
                if(resultCode==RESULT_OK){
                    List<String> pathList = Album.parseResult(data);
                    displayImage(pathList);
                }
                break;
            default: break;
        }
    }

    private void displayImage(List<String> pathList) {
        photoList.addAll(pathList);
        image_list.removeView(btn_imag_add);
        chooseable -= pathList.size();
        for (String imagepath:pathList) {
            if(imagepath!=null){
                Bitmap bitmap=BitmapFactory.decodeFile(imagepath);
                ImageView iv=new ImageView(view.getContext());
                iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
                iv.setImageBitmap(bitmap);
                image_list.addView(iv);
            }else{
                Toast.makeText(this.getContext(), "failed to get image", Toast.LENGTH_SHORT).show();
            }
        }
        if(chooseable>0){
            image_list.addView(btn_imag_add);
        }
    }

}
